<template>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      title="授权书详情"
      width="800px"
    >
    <Card title="基础信息">
      <Descriptions size="small" :column="1">
        <Descriptions.Item label="持有者"> {{ certificateData.holder }} </Descriptions.Item>
        <Descriptions.Item label="提供者"> {{ certificateData.provider }} {{ filingsName }} <a @click="handleCheckFilings" style="margin-left: 10px;">查询备案</a></Descriptions.Item>
        <Descriptions.Item label="创建时间"> {{ certificateData.created_at }} </Descriptions.Item>
        <Descriptions.Item label="生效时间"> {{ certificateData.start_time }} 至 {{ certificateData.end_time }} </Descriptions.Item>
        <Descriptions.Item label="签名"> {{ certificateData.signature }} </Descriptions.Item>
        <Descriptions.Item label="连接检测"> <span :style="{ color: validated? 'green': 'red' }">{{ validated? '检测成功': '检测失败' }}</span></Descriptions.Item>
      </Descriptions>
    </Card>
    <Card title="授权数据">
      <Card v-for="entity in certificateData.entities" :title=entity.name>
        <Descriptions size="small" :column="1">
          <Descriptions.Item label="名称"> {{ entity.name }} </Descriptions.Item>
          <Descriptions.Item label="字段"> {{ showFields(entity.fields) }} </Descriptions.Item>
          <Descriptions.Item label="限制条件"> {{ entity.ext_filter }} </Descriptions.Item>
        </Descriptions>
      </Card>
    </Card>

    <div style="margin-top: 30px; display: flex; justify-content: right;">
      <a-button @click="handleValidateCertificate" type="primary">连接检测</a-button>
    </div>
  
  </BasicDrawer>
  </template>
  
  <script lang="ts" setup>
    import { ref } from 'vue';
    import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
    import { Descriptions, Card } from 'ant-design-vue';
    import { validateCertificate, getCertificateFilings } from '@/api/connection'
  
    const certificateData = ref({});
    const certificateId = ref(0);
    const validated = ref(false);
    const filingsName = ref('');

    const [registerDrawer] = useDrawerInner(async (data) => {
      certificateId.value = data.record.id,
      certificateData.value = data.record.data;
      validated.value = data.record.validated;
    });
  
    function showFields(fields) {
      return fields.map(item => item.label || item.field).join('、');
    }

    async function handleValidateCertificate() {
      const res = await validateCertificate(certificateId.value);
      validated.value = res.validated;
    }

    async function handleCheckFilings() {
      const res = await getCertificateFilings(certificateId.value);
      if (res.name === null) {
        filingsName.value = `（未备案）`;
      } else {
        filingsName.value = `（${res.name}）`;
        const newWindow = window.open(res.url, '_blank');
        if (newWindow !== null) {
          newWindow?.focus();
        }
      }
    }
  
  </script>